package com.test.feishu;

import okhttp3.*;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

public class Robot {
    public static void main(String[] args) throws Throwable {
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("application/json");
        String secret = "RqehG5uc8czU68WtpcuFkh";
        int timestamp = (int) (System.currentTimeMillis() / 1000); // new Date().getTime() / 1000
        String msg = "test:客户123已销卡456失败，请及时处理";
        RequestBody body = RequestBody.create(mediaType, "{\"timestamp\": \"" + timestamp + "\",\"sign\": \"" + GenSign(secret, timestamp) + "\",\"msg_type\":\"text\",\"content\":{\"text\":\""+msg+"<at user_id=\\\"all\\\">所有人</at>\"}}");
        Request request = new Request.Builder()
                .url("https://open.feishu.cn/open-apis/bot/v2/hook/c92c03e0-077e-49d8-868c-5ab42de7e456")
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .build();
        Response response = client.newCall(request).execute();
    }

    private static String GenSign(String secret, int timestamp) throws NoSuchAlgorithmException, InvalidKeyException {
        //把timestamp+"\n"+密钥当做签名字符串
        String stringToSign = timestamp + "\n" + secret;

        //使用HmacSHA256算法计算签名
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(stringToSign.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
        byte[] signData = mac.doFinal(new byte[]{});
        return new String(Base64.encodeBase64(signData));
    }
}
